package com.tang.lease.common.utils;

import com.tang.lease.common.exception.LeaseException;
import com.tang.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;


import javax.crypto.SecretKey;
import java.util.Date;


public class JwtUtil {
    //Key的子类
    private static SecretKey secretKey = Keys.hmacShaKeyFor("B8XnVEZtn4xrmkJQvBGkmVZsSjGXT4km".getBytes());
    public static String createToken(Long userId,String username){
        String jwt = Jwts.builder().
                       setSubject("USER_INFO").
                       setExpiration(new Date(System.currentTimeMillis() + 3600000)).
                       claim("userId",userId).
                       claim("username",username).
                       signWith(secretKey, SignatureAlgorithm.HS256)
                       .compact();
        return jwt;
    }
    public static Claims parseToken(String jwt){
        if (jwt==null){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        try {
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(secretKey).build();
            Jws<Claims> claimsJws = jwtParser.parseClaimsJws(jwt);
            return claimsJws.getBody();
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }

    public static void main(String[] args) {
        System.out.println(createToken(2L,"user"));
    }
}
